﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.User;
using Provenance.Read.Api.Application.Command.User;
using Provenance.Read.Api.Dto.User;

namespace Provenance.Read.Api.Application.CommandHandler.User
{
    public class BackRoleCommandHandler : IRequestHandler<BackRoleCommand, ApiResult<BackRoleResponseDTO>>
    {
        private readonly IRoleRepository _roleRepository;
        private readonly IRolePermissionRepository _rolePermissionRepository;
        private readonly IPermissionRepository _permissionRepository;
        private readonly ILogger<BackRoleCommandHandler> _logger;
        private readonly IMapper _mapper;
        public BackRoleCommandHandler(IRoleRepository roleRepository, IRolePermissionRepository rolePermissionRepository, IPermissionRepository permissionRepository, ILogger<BackRoleCommandHandler> logger, IMapper mapper)
        {
            _roleRepository = roleRepository;
            _rolePermissionRepository = rolePermissionRepository;
            _permissionRepository = permissionRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult<BackRoleResponseDTO>> Handle(BackRoleCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var obj = await _roleRepository.GetAsync(x => x.RoleId == request.RoleId && !x.IsDeleted);
                if (obj == null)
                {
                    return ApiResult<BackRoleResponseDTO>.Failure("Role not found");
                }
                var result = _mapper.Map<BackRoleResponseDTO>(obj);
                var rolePermissionList = await _rolePermissionRepository.GetAllAsync(x => x.RoleId == request.RoleId&&!x.IsDeleted);
                var permissionIds = rolePermissionList.Select(x => x.PermissionId);
                result.PermissionIds = string.Join(',', permissionIds);
                return ApiResult<BackRoleResponseDTO>.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in BackRoleCommandHandler.Handle: " + ex.Message);
                return ApiResult<BackRoleResponseDTO>.Failure(ex.Message);
            }
        }
    }
}
